//
//  AccountManager.m
//  KiklinkApp
//
//  Created by LF on 14/10/22.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "AccountManager.h"
#import "SNSManager.h"
#import "API.h"
#import "LoginViewController.h"
#import "LoginNavigationViewController.h"
#import "BindPhoneViewController.h"

#import "UMSocialDataService.h"

NSString *const KEY_IS_LOGGED_IN = @"isLoggedIn";
NSString *const KEY_IS_THIRDPARTY = @"isThirdParty";
NSString *const KEY_THIRDPARTY_TYPE = @"ThirdPartyType";

NSString *const KEY_USERNAME = @"Username";
NSString *const KEY_PASSWORD = @"Password";

NSString *const KEY_TOKEN = @"Token";
NSString *const KEY_UID = @"UID";
NSString *const KEY_ICON_URL = @"IconUrl";
NSString *const KEY_PROFILE_URL = @"ProfileUrl";
NSString *const KEY_DISPLAY_NAME = @"DisplayName";


@implementation AccountManager

+(NSArray*) keyArray
{
    return [NSArray arrayWithObjects:KEY_IS_LOGGED_IN, KEY_IS_THIRDPARTY, KEY_USERNAME, KEY_PASSWORD, KEY_TOKEN, KEY_UID, KEY_ICON_URL, KEY_PROFILE_URL, KEY_DISPLAY_NAME, KEY_THIRDPARTY_TYPE, nil];
}

+ (void)openLoginUI
{
    [self openLoginUIWithCallback:^(int stateCode, NSString* word, id content)
     { }];
}

+ (void)openLoginUIWithCallback:(Callback)callback
{
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginStoryboard" bundle:nil];
    LoginNavigationViewController *loginNavi = [loginStoryboard instantiateInitialViewController];
    [loginNavi setLoginCallback:callback];
    [[self currentViewController] presentViewController:loginNavi animated:YES completion:nil];
}

+ (void)sendVerificationCodeTo:(NSString*)phoneNumber
{
    [API sendVerificationCodeToPhoneNumber:phoneNumber callback:^(int stateCode, NSString *word, id content) {
        if(stateCode == FAILURE_RETURN_ERRER_CODE)
        {
            showAlert(word);
        }
    }];
}

+ (void)firstLoginKiklinkWithUsername:(NSString*)username password:(NSString*)password callback:(Callback)callback
{
    [API loginKiklinkWithUsername:username Password:password Callback:^(int stateCode, NSString *word, id content) {
        if(stateCode == SUCCESS)
        {
            [self clearAccountInfo];
            [self setIsKiklinkLoggedin: YES];
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:username forKey:KEY_USERNAME];
            [userDefaults setObject:password forKey:KEY_PASSWORD];
            [userDefaults setObject:username forKey:KEY_DISPLAY_NAME];
            
            NSDictionary *user = [content objectForKey:@"user"];
            if(user != nil)
            {
                [userDefaults setObject:[user objectForKey:@"username"] forKey:KEY_DISPLAY_NAME];
                [userDefaults setObject:[user objectForKey:@"photo"] forKey:KEY_ICON_URL];
            }
            
            [userDefaults synchronize];
            
            KLLogStatic(self, @"Kiklink account saved");
        }
        else if (stateCode == FAILURE_RETURN_ERRER_CODE)
        {
            [self clearAccountInfo];	//有必要?
        }
        
        callback(stateCode, word, content);
    }];
}

//向callback传回是否能提供有效账户的信息，中间的按已有记录重登陆/要求用户更换账户等行为对其不可见
+ (void)autoLoginKiklinkWithCallback:(Callback)callback
{
    KLLogStatic(self, @"autoLoginKiklink");
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if(! [self isKiklinkLoggedin])
    {
        KLLogStatic(self, @"Account not exist");
        [self openLoginUIWithCallback:^(int stateCode, NSString *word, id content) {
            callback(stateCode, word, content);
        }];
        showAlert(@"请登录后使用此功能");
    }
    else{
        KLLogStatic(self, @"Account exist");
        
        if([self isThirdParty] == NO)
        {
            NSString *username = [userDefaults stringForKey:KEY_USERNAME];
            NSString *password = [userDefaults stringForKey:KEY_PASSWORD];
            
            [API loginKiklinkWithUsername:username Password:password Callback:^(int stateCode, NSString *word, id content) {
                if (stateCode == FAILURE_RETURN_ERRER_CODE)
                {
                    [self clearAccountInfo];
                    [self openLoginUIWithCallback:^(int stateCode, NSString *word, id content) {
                        callback(stateCode, word, content);
                    }];
                    showAlert(@"您的账号或密码已失效，请重新登录");
                }
                else
                {
                    callback(stateCode, word, content);
                }
            }];
        }
        else
        {
            NSString *thirdType = [userDefaults stringForKey:KEY_THIRDPARTY_TYPE];
            NSString *uid = [userDefaults stringForKey:KEY_UID];
            NSString *token = [userDefaults stringForKey:KEY_TOKEN];
            NSString *displayName = [userDefaults stringForKey:KEY_DISPLAY_NAME];
            
            [API thirdPartyLoginKiklinkWithType:thirdType id:uid token:token displayName:displayName sex:@0 Callback:^(int stateCode, NSString *word, id content) {
                if (stateCode == FAILURE_RETURN_ERRER_CODE)
                {
                    [self clearAccountInfo];
                    [self openLoginUIWithCallback:^(int stateCode, NSString *word, id content) {
                        callback(stateCode, word, content);
                    }];
                    showAlert(@"您的账号或密码已失效，请重新登录");
                }
                else
                {
                    callback(stateCode, word, content);
                }
            }];
        }
    }
}

+ (void)logoutKiklinkWithCallback:(Callback)callback
{
    [API logoutKiklinkWithCallback:^(int stateCode, NSString *word, id content) {
        if(stateCode == SUCCESS)
        {
            [self clearAccountInfo];
        }
        callback(stateCode, word, content);
    }];
}

+ (void)loginSNSWithPlatform: (NSString*) platform callback:(Callback)callback
{
    [SNSManager openSNSLoginUIWithPlatform:platform ViewController:[self currentViewController] callback:^(int stateCode, NSString *word, id content)
     {
         if (stateCode != SUCCESS) {
             callback(stateCode, word, content);
             return;
         }
         
         UMSocialResponseEntity *response = (UMSocialResponseEntity*) content;
         NSMutableDictionary *userDataDict = [[NSMutableDictionary alloc]init];
         
         if([platform isEqualToString:UMShareToSina])
         {
             NSDictionary *userData = [response.data objectForKey:@"sina"];
             
             if(userData == nil)
             {
                 callback(FAILURE_PARSE_ERROR, [StatusCode getWordByCode:FAILURE_PARSE_ERROR], content);
             }
             
             [userDataDict setValue:[userData objectForKey:@"username"] forKey:KEY_USERNAME];
             [userDataDict setValue:[userData objectForKey:@"usid"] forKey:KEY_UID];
             [userDataDict setValue:[userData objectForKey:@"icon"] forKey:KEY_ICON_URL];
             [userDataDict setValue:[userData objectForKey:@"profile_url"] forKey:KEY_PROFILE_URL];
         }
         else if([platform isEqualToString:UMShareToQQ])
         {
             //TODO
         }
         
         [SNSManager userTokenWithCallback:^(int stateCode, NSString *word, id content) {
             if(stateCode == SUCCESS)
             {
                 KLLogString(@"getToken success");
                 
                 [userDataDict setValue:word forKey:KEY_TOKEN];
                 UMSocialResponseEntity *response = (UMSocialResponseEntity*) content;
                 [userDataDict setValue:[response.data objectForKey:@"screen_name"] forKey:KEY_DISPLAY_NAME];
                 
                 NSString *thirdType = @"";
                 if(platform == UMShareToSina)
                 {
                     thirdType = @"weibo";
                 }
                 else if(platform == UMShareToQQ)
                 {
                     thirdType = @"qq";
                 }
                 [userDataDict setValue:thirdType forKey:KEY_THIRDPARTY_TYPE];
                 
                 [API thirdPartyLoginKiklinkWithType:thirdType id:[userDataDict objectForKey:KEY_UID] token:[userDataDict objectForKey:KEY_TOKEN] displayName:[userDataDict objectForKey:KEY_DISPLAY_NAME] sex:@0 Callback:^(int stateCode, NSString *word, id content) {
                     
                     if(stateCode == SUCCESS)
                     {
                         [AccountManager clearAccountInfo];
                         [AccountManager saveAccountInfo:userDataDict];
                         [AccountManager setIsKiklinkLoggedin:YES];
                         [AccountManager setIsThirdParty:YES];
                         
                         callback(stateCode, word, userDataDict);
                     }
                     else
                     {
                         callback(stateCode, word, content);
                     }
                     
                 }];
             }
             else{
                 callback(stateCode, word, content);
             }
         }];
         
         
     }];
}

+ (void)openBindPhoneUIWithUserData:(NSDictionary*)userData callback:(Callback)callback
{
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginStoryboard" bundle:nil];
    LoginNavigationViewController *veriNaviVC = [loginStoryboard instantiateViewControllerWithIdentifier:@"BindPhoneNaviVC"];
    [veriNaviVC setLoginCallback:callback];
    [veriNaviVC setUserData:userData];
    [[self currentViewController] presentViewController:veriNaviVC animated:YES completion:nil];
}

+ (BOOL)isSNSLoggedin	// ?
{
    KLLogStaticWithFormat(self, @"isLoggedinTo Weibo: %@", [SNSManager isLoggedInWithPlatform:UMShareToSina]?@"YES":@"NO");
    if([SNSManager isLoggedInWithPlatform:UMShareToSina])
    {
        return YES;
    }
    
    KLLogStaticWithFormat(self, @"isLoggedinTo QQ: %@", [SNSManager isLoggedInWithPlatform:UMShareToQQ]?@"YES":@"NO");
    if([SNSManager isLoggedInWithPlatform:UMShareToQQ])
    {
        return YES;
    }
    
    return NO;
}

//用户信息存储-------------------------------------------------------------

+ (NSDictionary*)accountInfo
{
    if(! [self isKiklinkLoggedin])
    {
        return  nil;
    }
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    return [userDefaults dictionaryRepresentation];
}

+ (void)saveAccountInfo:(NSDictionary*)dict
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *keys = [self keyArray];
    for(NSString *key in keys)
    {
        id value = [dict objectForKey:key];
        if(value != nil)
        {
            [userDefaults setObject:value forKey:key];
        }
    }
}

+ (void)clearAccountInfo
{
    KLLogStatic(self, @"clearAccountInfo");
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *keys = [self keyArray];
    for(NSString *key in keys)
    {
        [userDefaults removeObjectForKey:key];
    }
    
    [userDefaults synchronize];
}

+ (void)setIsKiklinkLoggedin:(BOOL)is
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    [userDefaults setBool:is forKey:KEY_IS_LOGGED_IN];
}

+ (BOOL)isKiklinkLoggedin
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    return [userDefaults boolForKey:KEY_IS_LOGGED_IN];
}

+ (void)setIsThirdParty:(BOOL)is
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    [userDefaults setBool:is forKey:KEY_IS_THIRDPARTY];
}

+ (BOOL)isThirdParty
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    return [userDefaults boolForKey:KEY_IS_THIRDPARTY];
}

//工具------------------------------------------------------------

+ (BOOL)isPasswordValid:(NSString*) target
{
    return [target length] >= 6;
}

+ (BOOL)isVerificationCodeValid:(NSString*) target
{
    return [target length] == 6;
}

+ (BOOL)isPhoneNumberValid:(NSString*) target
{
    //TODO: 高级检查
    return [target length] >= 11;
}

+ (UIViewController*)currentViewController
{
    // Find the top window (that is not an alert view or other window)
    UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow];
    if (topWindow.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(topWindow in windows)
        {
            if (topWindow.windowLevel == UIWindowLevelNormal)
                break;
        }
    }
    
    return [self topViewController:topWindow.rootViewController];
}

+ (UIViewController*)topViewController:(UIViewController*)rootViewController
{
    if (rootViewController.presentedViewController == nil) {
        return rootViewController;
    }
    
    if ([rootViewController.presentedViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *navigationController = (UINavigationController *)rootViewController.presentedViewController;
        UIViewController *lastViewController = [[navigationController viewControllers] lastObject];
        return [self topViewController:lastViewController];
    }
    
    UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController;
    return [self topViewController:presentedViewController];
}

//分享----------------------------------------------------------

+ (void) openSNSShareUIWithSharedText:(NSString*)text shareImage:(UIImage*)image
{
    [SNSManager openSNSShareUIWithSharedText:text shareImage:image sourceViewController:[self currentViewController]];
}

@end
